//
//  GitConfigParser.swift
//  GitTFGUI
//
//  Created by Samuel Richard Magny on 2015-09-02.
//  Copyright (c) 2015 Samuel Richard Magny. All rights reserved.
//

import Foundation

internal class GitTFConfigFileParser {
    
    private static let configHeaderRegex = "\\[(.*?)\\]"
    private static let configValueRegex = "\n\t(.*?) ="
    
    internal static let coreConfigKey = "core"
    internal static let gitTfServerConfigKey = "git-tf\"server\""
    internal static let gitTfConfigKey = "git-tf"
    
    internal static let gitTfServer_CollectionConfigKey = "collection"
    internal static let gitTfServer_ServerPathConfigKey = "serverpath"
    
    internal static func ParseFile(filePath:String) -> Dictionary<String, Dictionary<String, String>> {
        
        var configDict:Dictionary = Dictionary<String, Dictionary<String, String>>()
        let fileContent = getGitConfigFileContent(filePath)
        
        let configHeaders:Dictionary<String, String> = dictFromRegexMatches(fileContent,regexExpression: configHeaderRegex)
        for (key, content) in configHeaders
        {
            let configValues:Dictionary<String, String> = dictFromRegexMatches(content,regexExpression: configValueRegex, filterValueString:true)
            configDict[key] = configValues;
        }
        
        return configDict;
    }
    
    private static func getGitConfigFileContent(filePath:String)->String {
        let fileManager = NSFileManager.defaultManager();
        
        if(!fileManager.fileExistsAtPath(filePath)) {
            return "";
        }
        
        let fileContent:String = try! String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding)
        
        return fileContent;
    }
    
    private static func dictFromRegexMatches(sourceString:String, regexExpression:String, filterValueString:Bool = false)->Dictionary<String, String> {
        var resultDict = Dictionary<String, String>()
        
        let regEx = try? NSRegularExpression(pattern: regexExpression, options: NSRegularExpressionOptions())
        let matches = regEx!.matchesInString(sourceString, options: NSMatchingOptions(), range: NSMakeRange(0, sourceString.characters.count))
        
        let fileContentNS = (sourceString as NSString)
        
        for var i=0; i < matches.count; i++
        {
            let match: AnyObject = matches[i]
            
            let keyRange:NSRange = match.range
            var valRange:NSRange = NSRange()
            
            if(i == matches.count - 1) {
                valRange = NSMakeRange(keyRange.location + keyRange.length, fileContentNS.length - keyRange.location - keyRange.length)
            }
            else {
                let nextRange:NSRange = matches[i+1].range
                valRange = NSMakeRange(keyRange.location + keyRange.length, nextRange.location - keyRange.location - keyRange.length)
            }
            
            let key = trimPrivateChars(fileContentNS.substringWithRange(keyRange))
            let val = filterValueString ? trimPrivateChars(fileContentNS.substringWithRange(valRange)) : fileContentNS.substringWithRange(valRange)
            
            resultDict[key] = val;
        }
        
        
        return resultDict;
    }
    
    //TODO: Make this work with regex
    private static func trimPrivateChars(key:String)->String {
        var trimedKey = key.stringByReplacingOccurrencesOfString("\n", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
        trimedKey = trimedKey.stringByReplacingOccurrencesOfString("\t", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
        trimedKey = trimedKey.stringByReplacingOccurrencesOfString(" ", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
        trimedKey = trimedKey.stringByReplacingOccurrencesOfString("=", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
        trimedKey = trimedKey.stringByReplacingOccurrencesOfString("[", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
        trimedKey = trimedKey.stringByReplacingOccurrencesOfString("]", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
        
        return trimedKey
    }

    
}